<template>
  <div class="good-manger">
    <!-- 第二种上传 -->
    <el-upload action="#" list-type="picture-card" :before-upload="beforeAvatarUpload" :on-error="imgSaveToUrl">
      <img v-if="data.imageUrl" :src="data.imageUrl" :style="{ width, height }" />
      <el-icon v-else class="el-icon-plus avatar-uploader-icon" :style="{ width, height, 'line-height': height }"
        ><Plus
      /></el-icon>
    </el-upload>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, getCurrentInstance } from 'vue'
  import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
  // import {api} from '@/hooks/useCommon'
  import { ElMessage, UploadFile, UploadProps, UploadRawFile } from 'element-plus'
  const data = reactive({
    disabled: false,
    fileList: [],
    imageUrl: ''
  })
  const props = defineProps({
    width: {
      type: String,
      default: '100px'
    },
    height: {
      type: String,
      default: '100px'
    }
  })
  const emit = defineEmits(['change']);
  // 获取公共接口
  // @ts-ignore
  const { proxy } = getCurrentInstance()
  const api = proxy.$api
  // 文件上传前对文件进行限制操作
  const beforeAvatarUpload = (file: UploadRawFile) => {
    try {
      console.log(file, '限制操作')
      let reader = new FileReader()
      reader.onload = function (event) {
        // @ts-ignore
        let txt = event.target.result
        let img = document.createElement('img')
        // @ts-ignore
        img.src = txt
        img.onload = function () {
          console.log(img.width)
          console.log(img.height)
        }
      }
      reader.readAsDataURL(file)
      const isPNG = file.type === 'image/png'
      const isJPG = file.type === 'image/jpg'
      const isJPEG = file.type === 'image/jpeg'
      const flag = isPNG || isJPG || isJPEG
      console.log(flag, 'isJPG')
      const isLt2M = file.size / 800 / 800 < 2
      if (!flag) {
        ElMessage.error('上传商品图片只能是 PNG、JPG、JPEG 格式!')
      }
      if (!isLt2M) {
        ElMessage.error('上传商品图片大小不能超过 2MB!')
      }
      return flag && isLt2M
    } catch (error) {}
  }
  // 文件上传
  const imgSaveToUrl = async (error: Error, file: UploadFile) => {
    try {
      const formData = new FormData()
      // @ts-ignore
      formData.append('file', file.raw)
      const res = await api.uploadFile(formData)
      console.log(res, 'res')
      if (res.code == 200) {
        data.imageUrl = res.data?.url
				emit('change',data.imageUrl)
        ElMessage.success(res.msg)
      } else {
        ElMessage.error(res.msg)
      }
    } catch (error) {
      console.log(error)
      ElMessage.error('上传图片失败')
    }
  }
  const uploadTb = async (params: any, url: string | URL) => {
    console.log(params)
    // WARNING: For GET requests, body is set to null by browsers.
    return new Promise(function (resolve, reject) {
      var xhr = new XMLHttpRequest()
      xhr.withCredentials = true

      // xhr.addEventListener("readystatechange", function () {
      //   if (this.readyState === 4) {
      //     let result = xhr.responseText;
      //     console.log(JSON.parse(result), "xhr");
      //   }
      // });
      xhr.open('POST', url)
      xhr.setRequestHeader(
        'accept',
        'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
      )
      xhr.setRequestHeader('Content-type', 'multipart/form-data')
      xhr.setRequestHeader('accept-language', 'zh-CN,zh;q=0.9')
      xhr.setRequestHeader('authority', 's.taobao.com')
      xhr.setRequestHeader('Origin', 'https://s.taobao.com')
      xhr.setRequestHeader('Referer', 'https://www.taobao.com/?spm=a1z02.1.1581860521.1.2da2782dD7Wci')
      xhr.onload = function () {
        if (xhr.status === 200) {
          resolve(JSON.parse(xhr.responseText))
        } else {
          reject(new Error(xhr.statusText))
        }
      }
      xhr.onerror = function () {
        reject(new Error(xhr.statusText))
      }
      xhr.send()
    })
    // xhr.onreadystatechange = function () {
    //   console.log(xhr.readyState);
    //   //如果readyState是4并且响应码是200就接收
    //   if (xhr.readyState == "4" && xhr.status == "200") {
    //     //获取响应结果
    //     let result = xhr.responseText;
    //     console.log(JSON.parse(result), "xhr");
    //   }
    // };
  }
</script>

<style></style>
